package com.uduew.sjd.utils

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.ReclusionBean

object BatteryInfoCollector {
    // 获取完整电池信息
    fun getBatteryInfo(context: Context): ReclusionBean {
        val batteryStatus = context.registerReceiver(
            null,
            IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        )

        return parseBatteryStatus(batteryStatus)
    }

    // 解析电池状态
    private fun parseBatteryStatus(intent: Intent?): ReclusionBean {
        return if (intent != null) {
            val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
            val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
            val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
            val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)

            ReclusionBean(
                if (scale > 0) level.toDouble() / scale * 100 else 0.0,
                plugged == BatteryManager.BATTERY_PLUGGED_USB,
                isPlugged(plugged),
                isCharging(status)
            )
        } else {
            ReclusionBean(
                0.0,
                false,
                false,
                false
            )
        }
    }

    // 是否充电状态
    private fun isCharging(status: Int): Boolean {
        return status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL
    }

    // 是否连接电源
    private fun isPlugged(plugged: Int): Boolean {
        return plugged == BatteryManager.BATTERY_PLUGGED_AC ||
                plugged == BatteryManager.BATTERY_PLUGGED_USB ||
                plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS
    }


}
